package com.securecrt;

import java.io.IOException;
import java.util.ArrayList;

import com.securecrt.pojo.SaveSessionAdapter;
import com.securecrt.pojo.Savesession;
import com.securecrt.sql.SQLHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class SaveSession extends Activity {

	ArrayList<Savesession> list=new ArrayList<Savesession>();
	SQLHelper eventsData;
//	TextView output;
	ListView listSaveSession;
	String host,port, user,pass, mac, cipher;
	Button btBack, btHome,btNewConnect;
    SSHClient conn;
    ProgressDialog pro;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.savesession);
		
		eventsData=new SQLHelper(this);
    	cipher = getIntent().getExtras().getString("cipher");
    	mac = getIntent().getExtras().getString("mac");
        Cursor cursor=getEvents();
        showEvents(cursor);
        
        listSaveSession=(ListView)findViewById(R.id.listSaveSession);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
        listSaveSession.setOnItemClickListener(LoginServerAuto);
        
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);

		btBack=(Button)findViewById(R.id.btBack);
		btHome=(Button)findViewById(R.id.btHome);
		btBack.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				buttonBack();
			}});
		btHome.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				buttonHome();
			}});
		btNewConnect=(Button)findViewById(R.id.btNewConnect);
		btNewConnect.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				clickNewConnect();
			}
		});
	}
	private void clickNewConnect(){
		Intent i=new Intent(this, ssh2.class);
		startActivity(i);
	}
	private void buttonBack(){
		finish();
	}
	private void buttonHome(){
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();
		System.exit(0);
	}

	private void init(){
		list.clear();
		Cursor cursor=getEvents();
        showEvents(cursor);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
	}
	private void loadingShow(final Savesession item){
    	pro=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
    	Thread t = new Thread(new Runnable(){
            public void run() {
                try{
                	ssh2LoginAuto(item);
                }catch (Exception e) {
					e.printStackTrace();
				}
                pro.dismiss();
            }
        });
        t.start();
    }
	public boolean connectSSH(String host, int port, String username, String password, String cipher, String mac) throws IOException{
        try {
            conn = new SSHClient(username,password,host, port,cipher,mac);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            return false;
        }
	}
	private void ssh2LoginAuto(Savesession item){
		try {
			if(connectSSH(item.getHostname(),Integer.parseInt(item.getPort()),item.getUsername(),item.getPassword(), cipher, mac)){
				String classSelected = "com.securecrt.TERMINAL";
				Intent intent = new Intent(classSelected);
				intent.putExtra("server",item.getHostname());
				intent.putExtra("user", item.getUsername());
				intent.putExtra("port", String.valueOf(Integer.parseInt(item.getPort())));
				intent.putExtra("pass", item.getPassword());
				intent.putExtra("cipher", cipher);
				intent.putExtra("mac", mac);
				startActivity(intent);
				conn.disconnect();
			}else{
				Utils.showErrorMessage(this,"SSH Connect Fault.");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void showEx(final Savesession item){
		AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
		alertDialog.setTitle(getString(R.string.cfConnect)+"...");
		alertDialog.setMessage(getString(R.string.cfContent));
		alertDialog.setPositiveButton(getString(R.string.btAccept), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            	loadingShow(item);
            }
        });
        alertDialog.setNeutralButton(getString(R.string.btDelete), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,    int which) {
            	SQLiteDatabase db=eventsData.getWritableDatabase();
		    	db.delete(SQLHelper.TABLE, BaseColumns._ID + "=" +item.getId(), null);
            	init();
            }
        });
        alertDialog.setNegativeButton(getString(R.string.btCancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
	            dialog.cancel();
            }
        });
        alertDialog.show();
	}
	private OnItemClickListener LoginServerAuto=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
			// TODO Auto-generated method stub
			Savesession item=(Savesession)list.get(position);
			showEx(item);
		}
	};
    @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		eventsData.close();
	}

	private Cursor getEvents(){
		SQLiteDatabase db=eventsData.getReadableDatabase();
		Cursor cursor=db.query(SQLHelper.TABLE, null, null, null, null,null, null);
		startManagingCursor(cursor);
		return cursor;
	}
	private void showEvents(Cursor cursor){
		StringBuilder ret=new StringBuilder("Saved Events:\n\n");
		while(cursor.moveToNext()){
			long id =cursor.getLong(0);
			String hostname=cursor.getString(1);
			String port=cursor.getString(2);
			String username=cursor.getString(3);
			String password=cursor.getString(4);
			Savesession ss=new Savesession();
			ss.setId(id);
			ss.setHostname(hostname);
			ss.setPort(port);
			ss.setUsername(username);
			ss.setPassword(password);
			list.add(ss);
		}
	}
	
	
}
